"""
@Time : 2023/7/20 16:46
@Author : 憨憨李四
@Email : st124846@163.com
@File : base.py
@Project : python_workspace
@feature : 页面元素操作方法的封装。例如：查找元素，点击元素
@实现步骤：
"""
import os.path

from appium.webdriver.common.touch_action import TouchAction

from .get_log import logger
from .get_config import cf
from time import sleep, strftime
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


screenshots_dir_path = cf.screenshots_dir_path


class Base:
    """基础类"""

    def __init__(self, driver):
        self.driver = driver

    """等待方法"""

    def wait(self, s, msg="等待："):
        """
        :param s: 等待时间，单位：s
        :param msg: 注释说明
        :return:
        """
        sleep(s)
        logger.info(msg + f"{s} seconds.")

    """搜索网页元素方法"""

    def search_element(self, loc, msg='找到页面元素：'):
        """
        :param loc: 元素定位
        :param msg: 注释说明
        :return: element
        """
        try:
            logger.info(f"开始查找页面元素： {loc}")
            # 创建 Wait 对象
            # wait = WebDriverWait(self.driver, 2, 0.3)
            # wait.until(EC.visibility_of(self.driver.find_element(*loc)))
            element = self.driver.find_element(*loc)
            logger.info(msg + f"{loc}")
            return element
        except Exception as e:
            logger.warning(e)
            self.sava_pic()
            return None

    """点击网页元素方法"""

    def click_element(self, loc, msg='点击页面元素：'):
        """
        :param loc: 元素定位
        :param msg: 注释说明
        :return:
        """
        self.search_element(loc).click()
        logger.info((msg + f"{loc}"))

    """输入数据方法"""

    def send_data(self, loc, data, msg='给页面元素：'):
        """
        :param loc: 元素定位
        :param data: 数据
        :param msg: 注释说明
        :return:
        """
        self.search_element(loc).send_keys(data)
        logger.info(msg + f"{loc} 发送数据 {data}")

    """获取元素文本方法"""

    def get_element_text(self, loc, msg='获取页面元素文本：'):
        """
        :param loc: 元素定位
        :param msg: 注释说明
        :return: 页面元素文本
        """
        if self.search_element(loc) is None:
            return None
        else:
            text = self.search_element(loc).text
            logger.info(msg + f"{text}")
            return text

    """滑动方法"""
    def swipe_page(self, start_x, start_y, duration, end_x, end_y, msg='滑动页面操作'):
        """
        :param start_x:
        :param start_y:
        :param duration:
        :param end_x:
        :param end_y:
        :param msg:
        :return:
        """
        TouchAction(self.driver).press(x=start_x, y=start_y).wait(duration).move_to(x=end_x, y=end_y).release().perform()
        logger.info(msg + f'从起点 x={start_x} y={start_y} 滑到终点 x={end_x} y={end_y}')
        self.wait(1)

    """截图方法"""

    def sava_pic(self, msg='snapshot'):
        filename = screenshots_dir_path + '{0} - {1}.png'.format(msg, strftime('%Y_%m_%d_%H_%M_%S'))
        try:
            if not os.path.exists(filename):
                self.driver.save_screenshot(filename)
                logger.info(f"截图成功，图片保存路径为：{filename}")
            else:
                logger.info("截图失败！")
        except Exception as e:
            logger.warning(e)

    """检测是否有弹框"""

    def is_toast_show(self, tsast_msg, timeout=30, poll_frequency=0.5, msg='toast提示'):
        """
        :param tsast_msg: 要匹配的字段
        :param timeout: 最长等待时间
        :param poll_frequency: 检测间隔时间
        :param msg: 注释说明
        :return: True | False
        """
        locator = (By.XPATH, '//*[contains(text(), "%s)]' % tsast_msg)
        try:
            WebDriverWait(self.driver, timeout=timeout, poll_frequency=poll_frequency) \
                .until(EC.presence_of_element_located(locator))
            logger.info(msg + "成功找到！")
            return True
        except Exception as e:
            logger.error(e)
            logger.warning(msg + "未找到！")
            return False